<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">订单</el-breadcrumb-item>
      <el-breadcrumb-item>订单列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 按钮组 -->
    <span style="margin-top:15px">
        <el-button type="primary" size="medium" @click="finAll()">全部订单({{total}})</el-button>
        <el-button size="medium" v-for="item in orderStatus" :key="item.order_status" @click="findByStatus(item.order_status)">{{item.lable}}({{item.num}})</el-button>
        <el-button icon="el-icon-refresh" style="float: right"  @click="reload">刷新</el-button>
    </span>

    <!-- 卡片组件 -->
    <el-card class="box-card" style="margin-top:15px;margin-bottom:20px">
      <div slot="header" class="clearfix">
        <i class="el-icon-search"></i>
        <span>筛选查询</span>
      </div>
      <!-- 查询表单开始 -->
      <el-form :inline="true" :model="searchMap" class="demo-form-inline">
        
        <el-form-item label="输入搜索：">
          <el-input v-model="searchMap.id" placeholder="商品名称/商品货号"></el-input>
        </el-form-item>

        <el-form-item label="收货人">
          <el-input v-model="searchMap.receiverMobile" placeholder="收货人姓名/手机号码"></el-input>
        </el-form-item>

        <el-form-item label="提交时间">
          <el-date-picker type="date" placeholder="请选择时间" v-model="searchMap.pay_time" style="width: 100%;"></el-date-picker>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" icon="el-icon-search"  @click="onSubmit">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 按钮组2 -->
    <span style="float:right;">
        <el-button size="medium" @click="dialogVisible=true">拆分订单</el-button>
        <el-button size="medium" @click="showMergeOrder()">合并订单</el-button>
        <el-button size="medium">打印发货单</el-button>
        <el-button size="medium" @click="batchSen()">批量发货</el-button>
        <el-button size="medium">关闭订单</el-button>
        <el-button size="medium">删除订单</el-button>
    </span>

    <!-- 表格开始 -->
    <el-table :data="tableData" stripe style="width: 100%"  @selection-change="changeFun">>
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column prop="id" label="订单编号"></el-table-column>
      <el-table-column prop="createTime" label="提交时间" width="230">
          <template slot-scope="scope">
          {{scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户账号" width="170"></el-table-column>
      <el-table-column prop="payMoney" label="订单金额" width="140"></el-table-column>
      <el-table-column prop="payType" label="支付方式" width="170">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.payType === '0'" size="small">货到付款</el-tag>
          <el-tag v-else-if="scope.row.payType === '1'" type="warning" size="small">在线支付</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单来源" width="170">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sourceType === '1'" size="small">web</el-tag>
          <el-tag v-else-if="scope.row.sourceType === '2'" type="warning" size="small">app</el-tag>
          <el-tag v-else-if="scope.row.sourceType === '3'" type="info" size="small">微信公众号</el-tag>
          <el-tag v-else-if="scope.row.sourceType === '4'" type="success" size="small">微信小程序</el-tag>
          <el-tag v-else-if="scope.row.sourceType === '5'" type="danger" size="small">H5手机页面</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="130">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.orderStatus === '0'" size="small">待付款</el-tag>
          <el-tag v-else-if="scope.row.orderStatus === '1'" type="warning" size="small">待发货</el-tag>
          <el-tag v-else-if="scope.row.orderStatus === '2'" type="info" size="small">已发货</el-tag>
          <el-tag v-else-if="scope.row.orderStatus === '3'" type="success" size="small">已收货</el-tag>
          <el-tag v-else-if="scope.row.orderStatus === '4'" type="danger" size="small">已关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="设置">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="lookOrder(scope.$index, scope.row)" >查看订单</el-button>
          <el-button size="mini" type="text" @click="closeVisibleOrder(scope.$index, scope.row)">关闭订单</el-button>
        </template>
      </el-table-column>
    </el-table> 
    <!-- 表格结束 -->

    <!-- 分页开始 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="pageSizeList"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 分页结束 -->

    <!-- 拆分订单对话框 -->
    <el-dialog title="拆分订单" :visible.sync="dialogVisible" width="70%">
        <!-- 查询表单开始 -->
        <div style="align-content:center;">

          <el-form :inline="true" :model="searchMap2" class="demo-form-inline" >
              
              <el-form-item label="需要拆分订单">
                <el-input v-model="searchMap2.orderId" placeholder="输入订单号"></el-input>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" icon="el-icon-search"  @click="onSubmit2">搜索</el-button>
              </el-form-item>

          </el-form>

        </div>

        <!-- 表格开始 -->
        <el-table :data="tableData2" stripe style="width: 100%">
          <el-table-column prop="name" label="商品名称"></el-table-column>
          <el-table-column prop="snPrice" label="价格/货号" width="100"></el-table-column>
          <el-table-column prop="attribute" label="属性" width="90"></el-table-column>
          <el-table-column prop="num" label="数量" width="50"></el-table-column>
          <el-table-column prop="knum" label="库存" width="70"></el-table-column>
          <el-table-column prop="cnum" label="拆分数量" width="90">
            <template slot-scope="scope">
                <el-input v-model="scope.row.cnum"  size="small"/>
            </template>
          </el-table-column>
        </el-table>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="mergeOrderForm={}">重置</el-button>
        <el-button type="primary" @click="splitOrder()">拆分</el-button>
      </div>
    </el-dialog>

    <!-- 合并订单对话框 -->
    <el-dialog title="合并订单" width="50%" :visible.sync="dialogVisible2" @close="dialogClose2">
      <span class="fontStyle">当两个订单不一致时，合并后的订单信息（如：支付方式、配送方式、活动优惠等）以主订单为准</span>
      <el-form :model="mergeOrderForm">

        <el-form-item label="主订单：">
          <el-select v-model="mergeOrderForm.orderId1" placeholder="请选择" @change="selectChange">
            <el-option v-for="item in multipID" :label="item" :key="item" :value="item"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="从订单：">
          <el-select v-model="mergeOrderForm.orderId2" placeholder="请选择">
            <el-option v-for="item in multipID" :label="item" :key="item" :value="item"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="mergeOrderForm={}">重置</el-button>
        <el-button type="primary" @click="mergeOrder()">合并</el-button>
      </div>

    </el-dialog>

        <!-- 编辑界面 -->
    <el-dialog title="关闭订单" :visible.sync="closeVisible" width="50%" @click="closeDialog">
      <el-form label-width="120px">
        <el-form-item label="操作备注" label-width="120px">
          <el-input autocomplete="off" v-model="message" type="textarea" :autosize="{ minRows: 6, maxRows: 6 }"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" class="title" @click="closeOrder()">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  async created () {
    this.getOrderList()
  },
  data () {
    return {
      tableData: [], // 表格数据
      tableData2: [], // 拆分订单数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 页大小
      pageSizeList: [10, 20, 50, 100, 500], // 页大小列表
      total: 0, // 总记录数
      searchMap: {}, // 查询表单对象
      searchMap2: {}, // 拆分订单查询表单对象
      // 表单label的宽度
      formLabelWidth: '120px',
      // 订单的状态
      orderStatus: [],
      // 复选框ids
      multipID:[],
      // 合并订单表单
      mergeOrderForm: {},
      dialogVisible: false,
      dialogVisible2: false,
      closeVisible: false,
      message: '',
      order: {}
    }
  },
  methods: {
    // 查询列表
    async getOrderList () {
      this.searchMap.isDelete = 1;
      const { data: res } = await this.$http.post(`/orders/order/findPage?page=${this.currentPage}&size=${this.pageSize}`, this.searchMap)
      const { data: res2 } = await this.$http.get(`/orders/order/selectCount`)
      // const { data: res3 } = await this.$http.get(`/goods/category/findAllMenus`)
      // const { data: res2 } = await this.$http.get(`/goods/template/findAll`)
      this.tableData = res.rows
      this.total = res.total
      this.orderStatus = res2.data
      // console.log(res3);
      // this.cascaderOptions = res3.data
    },
    // 页大小改变事件
    handleSizeChange (val) {
      this.pageSize = val
      this.getOrderList()
    },
    // 页码改变事件
    handleCurrentChange (val) {
      this.currentPage = val
      this.getOrderList()
    },
    // 查询
    onSubmit () {
      this.getOrderList()
    },
    // 查询
    async onSubmit2 () {
      console.log(this.searchMap2.orderId);
      const { data: res } = await this.$http.get(`/orders/orderItem/findOrderItemByOrderId?orderId=${this.searchMap2.orderId}`)
      if (res.code !== 200) {
        return this.$message.error("查询失败")
      }
      console.log(res);
      this.$message.success("查询成功")
      this.tableData2 = res.data
    },
    //查看订单
    lookOrder (index, row) {
      this.$router.push({
        path: "/order/look_order",
        query: {
          orderId: row.id
        }
      })
    },
    closeVisibleOrder(index, row){
      this.order = row;
      this.closeVisible = true;
    },
    //显示需要合并的订单
    showMergeOrder () {
      if ( this.multipID.length<1) {
        this.$message.error("请选择合并的订单!")
        return 
      }
      if ( this.multipID.length===1) {
        this.$message.error("请至少选择两个以上需要合并的订单!")
        return 
      }
      this.dialogVisible2 = true
    },
    // 合并订单
    async mergeOrder () {
      if(this.mergeOrderForm.orderId1 == this.mergeOrderForm.orderId2){
        return this.$message.error("主订单和从订单不能一致")
      }
      const { data: res} =  await this.$http.get(`/orders/order/mergeOrders?orderId1=${this.mergeOrderForm.orderId1}&orderId2=${this.mergeOrderForm.orderId2}`);
      if (res.code !== 200) {
        return this.$message.error("合并失败，请重新选择")
      }
      this.$message.success("合并成功")
      this.getOrderList();
      this.dialogVisible2 = false
    },
    selectChange (item) {
      console.log(item);
    },
    // 拆分订单
    async splitOrder () {
      //得到需要拆分的数据
      let orders = []
      this.tableData2.forEach(order => {
        let o = {}
        o.id=order.id
        o.num = parseInt(order.cnum)
        orders.push(o)
      });
      //发送请求
      const { data: res} = await this.$http.post("/orders/order/splitOrders",orders);
      console.log(res);
      if (res.data === 200 ) {
        return this.$message.error("拆分失败")
      }
      this.$message.success("拆分成功")
      this.dialogVisible = false
      this.getOrderList()
    },
    handleClose () {},
    // 刷新
    reload () {
      window.location.reload()
    },
    //查看全部
    finAll () {
      this.searchMap = {}
      this.getOrderList();
    },
    // 查询根据状态`
    findByStatus (order_status) {
      this.searchMap.orderStatus = order_status
      this.getOrderList();
    },
    // 批量发货
    batchSen () {
      if ( this.multipID.length<1) {
        this.$message.error("请选择发货的订单")
        return 
      }
      // //只能选择代发货订单
      let count = 0;

      this.tableData.forEach(element => {
        this.multipID.forEach(element2 => {
          if(element.id === element2 && element.orderStatus !== '1'){
            count++;
          }
        })
      })
      if(count !== 0){
        this.$message.error("请选择待发货的订单!");
        return 
      }

      //路由跳转
      this.$router.push({
        path: '/order/batch_send',
        query: {
          ordersId: this.multipID
        }
      })
    },
    // 复选框的值
    changeFun(row){
		  let _this=this
		  _this.multipID=[] //每次改动重置ID
      row.forEach((item)=>{
      _this.multipID.push(item.id)
      })
    },
    // 关闭编辑、增加弹出框
    closeDialog() { 
        this.addressVisible = false
        this.closeDialog = false
    },
    // 对话框关闭
    dialogClose2 () {
      this.categoryForm = {}
    },
    closeOrder(){
        if(this.message == null && this.message == ''){
          return this.$message.error("请填写备注")
        }
        this.$confirm('此操作将永久关闭该订单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const { data: res } = await this.$http.post(`/orders/order/closeOrder?message=${this.message}`,this.order)
          if(res.code !== 200){
            return this.$message.error("关闭失败")
          }
          this.$message({
            type: 'success',
            message: '关闭成功!'
          });
          this.closeVisible = false;
          this.getOrderList()
        //   this.$router.push({
        //   path: '/order/order',
        //   query: {
        //     orderId: this.order.id
        //   }
        // })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消关闭'
          });    
          this.closeVisible = false;
          this.getOrderList()      
        });
      }
  },
  created () {
    this.getOrderList()
  }
}
</script>

<style scoped>
.fontStyle{
  font-size: 14px;
  padding-bottom: 14px;
}
</style>>
